'use strict';

var path     = require('path');
var util     = require('util');
var exec     = require('child_process').exec;

var GS_EXEC = 'gs';

var GS_CMD = '%s -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=%s %s-dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r%s "-sOutputFile=%s-%s.%s" "-f%s"';

var GS_PATHS = {
    linux: {
        ia32: 'gs-916-linux_x86',
        x64: 'gs-916-linux_x86_64'
    },
    win32: {
        ia32: 'gswin32c',
        x64: 'gswin64c'
    }
};

var gsPath = GS_PATHS[process.platform][process.arch];
gsPath = gsPath && path.join(__dirname, [GS_EXEC, process.platform, process.arch, gsPath].join('/')) || GS_EXEC;

function PdfImage (source, target, options, callback) {
    if (!source) {
        throw new Error('Can\'t convert PDF to Image without given a source.');
    }

    if (!target) {
        throw new Error('Can\'t convert PDF to Image without given a target.');
    }

    if (!options) {
        callback = function () {};
        options = {};
    } else if (!callback) {
        callback = options;
        options = {};
    }

    var dpi = options.dpi || 150;
    var quality = options.quality || 90;
    var format = options.format || PdfImage.PNG;

    exec(util.format(
        GS_CMD,
        gsPath,
        format.device,
        format.params ? util.format(format.params, quality) : '',
        dpi,
        target,
        '%d',
        format.ext,
        source
    ), callback);
};

PdfImage.PNG = {
    ext: 'png',
    device: 'pngalpha',
    params: ''
};
PdfImage.JPEG = {
    ext: 'jpg',
    device: 'jpeg',
    params: '-dJPEGQ=%d '
};

module.exports = PdfImage;
